<template>
  <div>
    <el-dialog
      title="新增权限组"
      v-model="showDrawer"
      :before-close="close"
      @close="close"
      top="70px"
      width="1000px"
      append-to-body
    >
      <el-steps :active="activeIndex" finish-status="success" simple>
        <el-step title="设置属性" />
        <el-step title="选择文档目录" />
        <el-step title="选择授权人员" />
        <el-step title="完成授权" />
      </el-steps>
      <div class="carousel-container">
        <el-carousel
          :height="fullHeight"
          arrow="never"
          ref="carouselGroup"
          trigger="click"
          :autoplay="false"
          indicator-position="none"
          :loop="false"
          :initial-index="initialIndex"
        >
          <el-carousel-item>
            <el-form
              ref="formBody"
              :model="formObj"
              :rules="formRules"
              label-width="90px"
            >
              <el-form-item prop="filePortfolioName" label="权限组名称">
                <el-input v-model="formObj.filePortfolioName" :maxlength="50" />
              </el-form-item>
              <el-form-item label="授权说明">
                <el-input
                  v-model="formObj.authorizationInstructions"
                  type="textarea"
                  :maxlength="500"
                />
              </el-form-item>
            </el-form>
          </el-carousel-item>
          <!-- S 选择文档目录 -->
          <el-carousel-item>
            <DocumentCategory
              ref="groupRef"
              :groupList="groupList"
              :groupTree="groupTree"
              @checkChange="checkChange"
            ></DocumentCategory>
          </el-carousel-item>
          <!-- E 选择文档目录 -->
          <!-- S 选择授权人员 -->
          <el-carousel-item>
            <AuthorizedOfficer
              ref="officerRef"
              :officer="officer"
              :add="true"
              :currentGroup="currentGroup"
              @confirmBtnPerson="confirmBtnPerson"
            ></AuthorizedOfficer>
          </el-carousel-item>
          <!-- E 选择授权人员 -->
          <el-carousel-item class="upload-carousel">
            <el-result icon="success" title="创建完成"> </el-result>
          </el-carousel-item>
        </el-carousel>
      </div>
      <div class="footer">
        <el-button
          v-if="initialIndex !== 0 && initialIndex !== 3"
          type="primary"
          size="small"
          @click="handelActiveItem('prev')"
        >
          上一步
        </el-button>
        <el-button
          v-if="initialIndex === 2"
          type="primary"
          size="small"
          @click="addBtn"
        >
          提交
        </el-button>
        <el-button
          type="primary"
          v-if="initialIndex !== 2 && initialIndex !== 3"
          size="small"
          @click="handelActiveItem('next')"
        >
          下一步
          <el-icon class="el-icon--right"><ArrowRight /></el-icon>
        </el-button>
        <el-button
          v-if="initialIndex === 3"
          type="primary"
          size="small"
          @click="resetAction"
        >
          继续创建
        </el-button>
        <el-button
          size="small"
          @click="close"
          v-if="initialIndex === 0 || initialIndex === 3"
          >{{ initialIndex === 0 ? '取消' : '返回' }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="addGroup">
import DocumentCategory from './documentCategory.vue'
import AuthorizedOfficer from './authorizedOfficer.vue'
import { addGroup, getGroupDetail, getGroupTree } from '@/api/fileManager'
import { handleTree } from '@/utils/index'

const emits = defineEmits()
const props = defineProps({
  currentSetp: {
    type: Number,
    default: () => {
      return 1
    },
  },
  currentGroup: {
    type: Object,
    default: () => {
      return {}
    },
  },
  drawer: {
    type: Boolean,
    default: false,
  },
})
const officer = ref({})
const store = useStore()
const { proxy } = getCurrentInstance()
const fullHeight = ref(
  (document.documentElement.clientHeight || document.body.scrollHeight) -
    450 +
    'px'
)
let initialIndex = ref(0) // 步骤内容索引
const activeIndex = ref(0) // 步骤索引
const _checkedNodes = ref([])

const showDrawer = computed({
  get() {
    return props.drawer
  },
  set(val) {
    emits('update:drawer', val)
  },
})
const setpMap = {
  add: 0, // 新增操作
  edit: 1, // 编辑
  cate: 2, // 修改文档目录
  person: 3, // 修改关联人员
}
const editPerson = ref([])
const formObj = ref({})
const formRules = ref({
  filePortfolioName: [
    { required: true, trigger: 'blur', message: '请输入权限组名称' },
  ],
})

// 是否是新增
const isAdd = computed(() => {
  return _currentSetp.value === setpMap.add
})
const _currentSetp = computed(() => {
  return props.currentSetp
})

onMounted(() => {
  open()
})

function checkChange(checkedNodes) {
  _checkedNodes.value = checkedNodes
}
function handelActiveItem(action) {
  if (action === 'next') {
    // 检查是否填写权限组名称
    if (initialIndex.value === 0) {
      proxy.$refs['formBody'].validate((valid) => {
        if (valid) {
          initialIndex.value++
          activeIndex.value++
          setCarousel(initialIndex.value)
        } else {
          proxy.$message.warning('请按照提示正确输入数据')
        }
      })
    } else {
      initialIndex.value++
      activeIndex.value++
      setCarousel(initialIndex.value)
    }
  } else {
    initialIndex.value--
    activeIndex.value--
    setCarousel(initialIndex.value)
  }
}
// 设置触发步骤
function setCarousel(index) {
  proxy.$refs.carouselGroup.setActiveItem(index)
}
function open() {
  /* setTimeout(() => {
    setCarousel(_currentSetp.value - 1)
  }, 0) */
  // 新增重置属性
  resetFormValue()
  // 文档目录授权
  _getGroupTree(-2)
  // 查询权限组已授权人员
  _getGroupDetail(-2)
}

const groupTree = ref([]) // 树形类别
const groupList = ref([]) // 所有类别
/** 获取类别下拉树结构 */
function _getGroupTree(id) {
  getGroupTree(id).then((response) => {
    let fileCategoryList = response.data.fileCategoryList
    fileCategoryList.forEach((element) => {
      element['allowDownloads'] = '0'
      element['allowUpload'] = '0'
      element['allowView'] = '0'
      element['allowPreview'] = '0'
      // element['allowDeleted'] = '0'
      element['allowPrint'] = '0'
    })
    groupList.value = fileCategoryList
    groupTree.value = handleTree(response.data.fileCategoryList, 'id')
  })
}
// 查询权限组已授权人员
function _getGroupDetail(id) {
  getGroupDetail(id).then((res) => {
    officer.value = res.data
  })
}
function resetFormValue() {
  formObj.value = {}
}
// 新增权限组数据
function addBtn() {
  const filePortfolio = {
    filePortfolioName: formObj.value['filePortfolioName'],
    authorizationInstructions: formObj.value['authorizationInstructions'],
  }
  let fileCategoryPortfolioMapperList = []
  console.log(_checkedNodes.value)
  _checkedNodes.value.forEach((element) => {
    console.log(element)
    console.log(element.allowDownloads)
    const _params = {
      allowDownloads: element.allowDownloads ? element.allowDownloads : '0',
      allowUpload: element.allowUpload ? element.allowUpload : '0',
      allowView: element.allowView ? element.allowView : '0',
      allowPreview: element.allowPreview ? element.allowPreview : '0',
      // allowDeleted: element.allowDeleted ? element.allowDeleted : '0',
      allowPrint: element.allowPrint ? element.allowPrint : '0',
      fileCategoryId: element.id,
      fileCategoryName: element.categoryName,
      filePortfolioName: formObj.value['filePortfolioName'],
    }
    fileCategoryPortfolioMapperList.push(_params)
  })
  console.log(fileCategoryPortfolioMapperList)
  let portfolioUserMapperList = editPerson.value
  const params = {
    filePortfolio,
    fileCategoryPortfolioMapperList,
    portfolioUserMapperList,
  }
  _addGroup(params)
}

function _addGroup(params) {
  addGroup(params).then((res) => {
    if (res.success) {
      initialIndex.value++
      activeIndex.value++
      setCarousel(initialIndex.value)
      emits('refreshList')
    }
  })
}
function resetAction() {
  resetBase()
  setCarousel(initialIndex.value)
  // 文档目录授权
  _getGroupTree(-2)
}
function confirmBtnPerson(val) {
  // 编辑关联人员
  editPerson.value = val
}
function close() {
  resetBase()
  setCarousel(initialIndex.value)
  emits('close')
}
function resetBase() {
  proxy.$refs.formBody.resetFields()
  proxy.$refs.groupRef.resetCate()
  proxy.$refs.officerRef.clearHandle()
  proxy.$refs.officerRef.rightValue = []
  activeIndex.value = 0
  initialIndex.value = 0
  editPerson.value = []
  resetFormValue()
}
</script>

<style scoped lang="scss">
.carousel-container {
  padding: 20px 0;
}
.footer {
  display: flex;
  justify-content: flex-end;
}
</style>
